//
//  CZComposeController.swift
//  weiBo
//
//  Created by apple on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComposeController: UIViewController, UITextViewDelegate {

    //懒加载配图
    private lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        view.backgroundColor = UIColor.whiteColor()
        
        return view
    }()
    
    //懒加载toolbar
    @available(iOS 9.0, *)
    
    private lazy var toolBar: CZComposeToolBar = {
        let view = CZComposeToolBar(frame: CGRectZero)
        
        
        return view
    }()
    //懒加载控件
    private lazy var rightButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //  设置button文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.frame.size = CGSize(width: 45, height: 30)
        
        return btn
    }()
    //懒加载titleView
    private lazy var titleView:UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        if let name = CZUserCountViewModel.sharedUserAccount.userAcount?.name {
            let title: String = "发微博\n\(name)"
            //获取name的范围
            let range = (title as NSString).rangeOfString(name)
            //创建副文本对象
            let attributedStr = NSMutableAttributedString(string: title)
            //修改颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            //设置字体大小
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            //设置label的副文本
            label.attributedText = attributedStr
        
        }else {
            label.text = "发微博"
        }
    
        //  多行显示
        label.textAlignment = .Center
        label.numberOfLines = 0
        label.sizeToFit()
    
    
        return label
    }()
    
    //懒加载textView
    private lazy var textView: CZComposeTextView = {
        let view = CZComposeTextView()
        view.delegate = self
        view.placeHolder = "请输入 内容"
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(14)
        
        return view
    }()
    //懒加载表情键盘
    private lazy var emoticonKeyboard: CZEmoticonKeyBoard = {
        let vc = CZEmoticonKeyBoard()
        vc.frame.size = CGSize(width: self.textView.frame.size.width, height: 216)
        
        return vc
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        navigationItem.rightBarButtonItem?.enabled = false
        
        //监听键盘的改变通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听表情按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSectedEmoticon:", name: DidSeletedEmoticonNotification, object: nil)
        
        //监听删除按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelectedDeleteEmoticonButtonNotification, object: nil)
    }
    
    //键盘改变的方法
    @objc private func keyboardChageFrame (not: NSNotification){
        let keyBoardFrame = (not.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let animationDuration = (not.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue

        
        //更新约束
            //更新约束
            toolBar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - view.frame.size.height)
            }
            //设置动画
            UIView.animateWithDuration(animationDuration) { () -> Void in
                self.view.layoutIfNeeded()
        }
    }
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    private func setUpUI() {
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.titleView = titleView
        view.addSubview(textView)
        
        textView.addSubview(pictureView)
        
      
        
            view.addSubview(toolBar)
        //  设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
        }
        //picture设置约束
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
            toolBar.snp_makeConstraints { (make) -> Void in
                make.bottom.equalTo(view)
                make.leading.equalTo(view)
                make.trailing.equalTo(view)
                make.height.equalTo(44)
            }
            
            toolBar.didSeletedButtonClosure = {[weak self] (type: CZComposeToolBarButtonType) in
                switch type {
                case .picture:
                    print("点击了图片")
                    self?.didSelectedPicture()
                    
                    
                case .Mention:
                    print("Mention")
                case .Trend:
                    print("@")
                case .Emoticon:
                    print("点击了表情")
                    self?.didSelectionEmoticon()
                case .Add:
                    print("添加")
                }           
            }
        
        pictureView.didSelectAddImageClosure = {[weak self] in
            self?.didSelectedPicture()
        }
        
        
        
    }
    
    // MARK -点击事件
    
    @objc private func cancelAction() {
        self.textView.endEditing(true)
        self.dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    @objc private func sendAction() {
        
        if pictureView.images.count > 0 {
            
            
            
            //   准备参数
            let accesstoken = CZUserCountViewModel.sharedUserAccount.access_token!
            let status = textView.emotionText
            //  请求发送微博接口
            
            SVProgressHUD.show()
            let image = pictureView.images.first!

            CZNetWorkTools.shareTools.upload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络异常")
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
        
        }else {
            //   准备参数
            let accesstoken = CZUserCountViewModel.sharedUserAccount.access_token!
            let status = textView.emotionText
            
            //  请求发送微博接口
            
            SVProgressHUD.show()
            CZNetWorkTools.shareTools.update(accesstoken, status: status, callBack: { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络异常")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
        
        }
      
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    //监听textView的变化
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    //监听删除按钮的方法
    func didSelectedDeleteEmoticon() {
        textView.deleteBackward()
        
    }
}

extension CZComposeController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    //选择表情按钮
    func didSelectionEmoticon() {
        if textView.inputView == nil{
            textView.inputView = emoticonKeyboard
            toolBar.showEmoticonIcon(true)
           
        }else {
            textView.inputView = nil
            toolBar.showEmoticonIcon(false)
        }
        
            textView.becomeFirstResponder()
            textView.reloadInputViews()
        
    }
    
    //选择照片按钮
    func didSelectedPicture() {
        let vc = UIImagePickerController()
        vc.delegate = self
        if UIImagePickerController.isSourceTypeAvailable( .Camera) {
            vc.sourceType = .Camera
        }else {
            vc.sourceType = .PhotoLibrary
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置可用")
        }else if UIImagePickerController.isCameraDeviceAvailable( .Rear) {
            print("后置可用")
        }else {
//            print("摄像头不可用")
        }
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    //实现代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
        //获取图片的二进制数据 保存到桌面
//        let data = UIImagePNGRepresentation(image)
//        data?.writeToFile("/Users/apple/Desktop/2.png", atomically: true)
        
//        let scaleImage = scaleImageWithWidth(image, scaleWidth: 300)
        let scaleImage = image.scaleImageWithWidth(300)
        
//        let data = UIImagePNGRepresentation(scaleImage)
//        data?.writeToFile("/Users/apple/Desktop/3.png", atomically: true)
        
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //监听表情改变的方法
    @objc func didSectedEmoticon(not: NSNotification) {
        let obj = not.object as? CZEmoticon
        guard let emotion = obj else {
            return
        }
        
        textView.insertEmoticon(emotion)
            
    
}

}